<script lang="ts" setup>
    import { ref, reactive, onMounted, inject, computed,watch } from 'vue';
    import {IconCaretDown} from '@arco-design/web-vue/es/icon';
    import MetricsTreeIcon from '@/assets/images/metrics_tree_icon.svg';
    import API from '@/services';
    import {debounce} from 'lodash'
    const emit = defineEmits(['handleIndex'])
    const props = defineProps({
        groupId: {
            type: String || Boolean || undefined
        }
    })
    const sortTreeOption : any = inject('sortTreeOption')

    const rootTreeId = ref<any>()
    const searchKey = ref(''); 
    const fieldNames = {value: 'id', label: 'name'}

    const originTreeData = ref()

    // 指标树过滤操作
    const index = ref()
    const treeCurrentKey = ref<any>([])
    const clickTreeNode = (selectedKeys:any, e:any) => {//点击树节点触发的时间
      treeCurrentKey.value = selectedKeys // 选中节点的key值
      if (e.node?.children && e.node.hasOwnProperty('number')) {
        treeCards.value.selectNode(selectedKeys[0], false)
      }
    }
    const treeData = computed(() => {
        if (!searchKey.value) return originTreeData.value;
        return searchData(searchKey.value);
      })
    const changeGroupTree = (v:any) => {
        originTreeData.value = []
        searchKey.value = ''
        getTreeNode(v)
    }
    const getTreeNode = async (rootId:any) => {
        try {
            const {code, data} = await API.metricsGroup.getMetricsGroupGetGroupWithMetricsByRootId({
                rootId
            })
            if (code === 200) {
                
                originTreeData.value = [{...data}]
            }
        } catch (error) {
            
        }
    }

    const handleLeafNode = debounce ((v:any) => {
        if (!v?.children) {
            emit('handleIndex', v)
        }
    }, 2000, {
        'leading': true,
        'trailing': false
    })
    const treeCards :any =ref()
    // 前端搜索树
    const getMatchIndex = (title:string) => {
         if (!searchKey.value) return -1;
        return title.toLowerCase().indexOf(searchKey.value.toLowerCase());
    }
    const handleSearch = (v:any) => {
        searchData(searchKey.value)
    }
    const searchData = (keyword:string) => {
        const loop = (data:any) => {
          const result :any= [];
          data.forEach((item:any) => {
            if (item.name.toLowerCase().indexOf(keyword.toLowerCase()) > -1) {
              result.push({...item});
            } else if (item.children) {
              const filterData = loop(item.children);
              if (filterData.length) {
                result.push({
                  ...item,
                  children: filterData
                })
              }
            }
          })
          return result;
        }

        return loop(originTreeData.value);
    }
    watch(
        () => props.groupId, 
        (val) => {
            rootTreeId.value = val || sortTreeOption.value[0].id
            if (sortTreeOption.value?.length && !originTreeData.value?.length) {
                getTreeNode(val || sortTreeOption.value[0].id)
            }
        },
        {
            immediate: true
        }
        )
    
</script>

<template>
    <div class="pt-12 prl-15">
        <a-select 
            v-model="rootTreeId"
            :options="sortTreeOption"
            :field-names="fieldNames"
            @change="changeGroupTree"
            size="small"
        >
            <template #arrow-icon>
                <icon-caret-down />
            </template>
        </a-select>

        <a-input-search
            v-model="searchKey" 
            placeholder="请输入"
            class="mt-12"
            size="small"
            allow-clear
            @search="handleSearch"
        />

        <div class="mt-16 pt-12 maxHeight400 overflow-auto cardTree">
            <a-tree 
                :data="treeData"
                :fieldNames="{
                    key: 'id',
                    title: 'name',
                }"
                v-if="treeData?.length"
                size="mini"
                node-key="id"
                :block-node="true"
                :default-selected-keys="treeCurrentKey"
                @select="clickTreeNode"
                :defaultExpandAll="true"
                ref="treeCards"
            >
                <template #title="nodeData">
                        <template v-if="index = getMatchIndex(nodeData?.name), index < 0">

                            <span v-if="nodeData.hasOwnProperty('number')" class="node-tree-name">
                                {{nodeData.name}} ({{nodeData.number}})
                            </span>
                            <span v-else class="node-tree-name"
                                @click="(e:any) => {
                                    e.preventDefault()
                                    e.stopPropagation()
                                    handleLeafNode(nodeData)
                                }"
                            >   <img class="metricsIcon" :src="MetricsTreeIcon" alt="">
                                {{nodeData.name}}
                            </span>
                        </template>
                        <template v-else>
                            <span class="afterSerachText" @click="(e:any) => {
                                e.preventDefault()
                                e.stopPropagation()
                                handleLeafNode(nodeData)
                            }">
                            <span v-if="nodeData.number" class="node-tree-name">
                                {{nodeData.name?.substr(0, index)}} ({{nodeData.number}})
                            </span>
                            
                            <span v-else class="node-tree-name"

                            >
                                <img class="metricsIcon" :src="MetricsTreeIcon" alt="" />
                                {{nodeData.name?.substr(0, index)}}
                            </span>
                            
                                <span style="color: var(--color-primary-light-4);">
                                    {{ nodeData?.name?.substr(index, searchKey.length) }}
                                </span>
                                <span>
                                    {{ nodeData?.name?.substr(index + searchKey.length) }}
                                </span>
                            </span>
                            
                        </template>
                    <!-- </a-tooltip> -->
                </template>
            </a-tree>
        </div>
    </div>
</template>

<style>
.metricsIcon {
    width: 10px;
    height: 10px;
    vertical-align: initial;
}
.arco-tree-node-title {
    overflow: hidden;
}
.arco-tree-node-title-text {
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
}
.cardTree .arco-tree-node {
    line-height: 30px;
}
</style>